<?php

class FrontendController extends Module
{
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            // если используется проверка прав, не забывайте разрешить доступ к
            // действию, отвечающему за генерацию изображения
            array('allow',
                'actions'=>array('captcha'),
                'users'=>array('*'),
            ),
            array('allow',
                'users'=>array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    public function  actionRegistration()
    {

        $model = new User;
        if(isset($_POST['User']))
        {
            $model->attributes = $_POST['User'];
            $token = sha1(uniqid($model->name,true));
            $model->activationKey = $token;
            if($model->save())
            {
                $mail = new YiiMailer();
                $mail->protocol = 'smtp';
                $mail->port = 465;
                $mail->charset = 'utf-8';
                $mail->SMTPSecure = 'ssl';
                $mail->mail_domain = Yii::app()->getModule('user')->params->mailDomain;
                $mail->login = Yii::app()->getModule('user')->params->adminEmail;
                $mail->name = Yii::app()->params->Brand;
                $mail->password = Yii::app()->getModule('user')->params->adminEmailPass;
                $mail->from = Yii::app()->getModule('user')->params->adminEmail;
                $mail->subject = Yii::t('UserModule.base','Account activation');
               // $mail->body = "";
                $mail->html = "<p>".Yii::t('UserModule.base','Account activation')."</p>
                               <p>".Yii::t('UserModule.base','To activate an account, please please link')."  <b><a href='".Yii::app()->createAbsoluteUrl('user/activation/',array('token'=>$token))."'>".Yii::t('UserModule.base','Account activation')."</a></b></p>
                               <p>".Yii::t('UserModule.base','P.S. Sincerely, site administration.')."</p>";
                $mail->message = "тестовое сообщение2";
                $mail->recipient = $model->name;
                $mail->to = $model->email;
                //$mail->debug = true;
                $mail->send();
                if($mail){

                    Yii::app()->user->setFlash('message',Yii::t('UserModule.base','You were sent an activation email'));
                    $this->redirect(Yii::app()->createUrl('/user/registration/success'));
                }
            }
        }
        $this->render('registration',array('model'=>$model));
    }
    public function actions()
    {
        return array(
            'captcha'=>array(
                'class'=>'CCaptchaAction',
            ),
        );
    }

    public function actionLogin()
    {
        if(Yii::app()->user->isGuest)
        {
        $model=new LoginForm;

        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login',array('model'=>$model));
        }
        else
        {
            $this->redirect(Yii::app()->createUrl('/site/index'));
        }
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    /*
     * Метод Activation, проверяет поученный токен в БД
     * В случае успеха (Если запись не устарела в течений дня) активирует уч.запись и обновляет поле update_time
     * В противном случае,удаляет неативированную запись и выводит сообщение пользователю.
     *
     */
    public function actionActivation()
    {
        if(isset($_GET['token']))
        {
            $sql = "SELECT id,name,login,email,active,activationKey,create_time FROM {{user}} WHERE activationKey=:key";
            $q = Yii::app()->db->createCommand($sql);
            $q->bindParam(':key',$_GET['token']);
            $dataReader = $q->queryRow();
            if($dataReader){

                    if($dataReader['active'] == 0)
                    {
                        $timestamp = time();
                        $create_time = strtotime($dataReader['create_time']);
                        $time = $timestamp-$create_time;

                        if($time < 3600)
                        {
                            $dateformat = date('Y-m-d H:i:s',$timestamp);
                            $sql = "UPDATE {{user}} SET active=1,update_time=:now WHERE id=:id";
                            $command = Yii::app()->db->createCommand($sql);
                            $command->bindParam(':id',$dataReader['id']);
                            $command->bindParam(':now',$dateformat);
                            $command->execute();
                            if($command)
                            {
                                Yii::app()->user->setFlash('message',Yii::t('UserModule.base','Congratulations account activation was successful!'));
                                $this->redirect(Yii::app()->createUrl('/user/activation/success'));
                            }
                        }
                        else{
                            $sql = "DELETE FROM {{user}} WHERE id=:id";
                            $command = Yii::app()->db->createCommand($sql);
                            $command->bindParam(':id',$dataReader['id']);
                            $command->execute();
                            throw new CHttpException(408,Yii::t('UserModule.base','The activation link is outdated. Please re-register again.'));
                        }
                    }
                    else
                    {
                        throw new CHttpException(403,'Forbidden.');
                    }
            }
            else
            {
                throw new CHttpException(410,Yii::t('UserModule.base','The activation link is outdated. Please re-register again.'));
            }
        }
        $this->render('activation');
    }
    /**
     * Метод Forgot используется для восстановления пароля
     * Отправляет токен
     */
    public function actionForgot()
    {
        $model = new ForgotForm();
        if(isset($_POST['ForgotForm']))
        {
            $model->attributes = $_POST['ForgotForm'];
            if($model->validate())
            {
                $token = sha1(uniqid($model->email,true));
                $now = date('Y-m-d H:i:s');

                $mail = new YiiMailer();
                $mail->protocol = 'smtp';
                $mail->port = 465;
                $mail->charset = 'utf-8';
                $mail->SMTPSecure = 'ssl';
                $mail->mail_domain = Yii::app()->getModule('user')->params->mailDomain;
                $mail->login = Yii::app()->getModule('user')->params->adminEmail;
                $mail->name = "аскар";
                $mail->password = Yii::app()->getModule('user')->params->adminEmailPass;
                $mail->from = Yii::app()->getModule('user')->params->adminEmail;
                $mail->subject = 'Password Recovery';
                $mail->html = "<p>".Yii::t('UserModule.base','Password recovery.')."</p>
                               <p>".Yii::t('UserModule.base','To continue, recovery password, please click here')." <b><a href='".Yii::app()->createAbsoluteUrl('user/frontend/recovery',array('token'=>$token))."'>".Yii::t('UserModule.base','Password recovery.')."</a></b></p>
                               <p>".Yii::t('UserModule.base','P.S. Sincerely, site administration.')."</p>";
                $mail->recipient = $model->email;
                $mail->to = $model->email;
                //$mail->debug = true;
                $mail->send();
                if($mail){
                    $sql = "UPDATE {{user}} SET activationKey=:token,update_time=:now WHERE email=:email";
                    $command = Yii::app()->db->createCommand($sql);
                    $command->bindParam(':token',$token);
                    $command->bindParam(':now',$now);
                    $command->bindParam(':email',$model->email);
                    $command->execute();
                    Yii::app()->user->setFlash('message',Yii::t('UserModule.base','You were sent an email with further instructions.'));
                    $this->redirect(Yii::app()->createUrl('/user/registration/success'));
                }
            }
        }
        $this->render('forgot',array('model'=>$model));
    }

    /**
     * Метод восстанавливает забытый пароль
     * Проверяет токен(Срок действия токена 1 час)
     * Принимает от пользователя новый пароль
     */
    public function actionRecovery()
    {
        if(isset($_GET['token']))
        {
            $token = strip_tags($_GET['token']);
            $sql = "SELECT * FROM {{user}} WHERE activationKey=:token";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindParam(':token',$token);
            $dataReader = $command->queryRow();
            if($dataReader)
            {
                $now_time = time();
                $upd_time = strtotime($dataReader['update_time']);
                $remained = $now_time-$upd_time;
                if($remained < 3600)
                {
                    $model = User::model()->findByPk($dataReader['id']);
                    if(isset($_POST['User']))
                    {
                       $model->attributes = $_POST['User'];

                       if($model->save())
                       {
                           Yii::app()->user->setFlash('message',Yii::t('UserModule.base','A new password was saved successfully. You can log in to your account using your new password.'));
                           $this->redirect(Yii::app()->createUrl('/user/registration/success'));
                       }
                    }
                    $model->setAttribute('password','');
                    $this->render('recovery',array('model'=>$model));
                }
                else
                {
                    throw new CHttpException(408,Yi::t('UserModule.base','Query date. Please try again restore again.'));
                }
            }
        }
    }

    public function actionSuccess()
    {
        if(Yii::app()->user->hasFlash('message'))
        {
            $message = Yii::app()->user->getFlash('message');
            $this->render('success', array('success'=>$message));
        }else{
            throw new CHttpException(404,'Page not found');
        }
    }
    public function actionFailed()
    {
        if(Yii::app()->user->hasFlash('error'))
        {
            $error = Yii::app()->user->getFlash('error');
            $this->render('failed', array('error'=>$error));
        }else{
            throw new CHttpException(404,'Page not found');
        }
    }

    public function actionError()
    {
        if($error=Yii::app()->errorHandler->error)
        {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionProfile()
    {
        $model=new User('profile');
        $this->render('profile',array('model'=>$this->loadModel(Yii::app()->user->id)));
    }


    public function loadModel($id)
    {
        $model = User::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }


    public function actionUpdateOwnProfile($id)
    {
        $model=$this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            $model->image=CUploadedFile::getInstance($model,'avatar');
            $newname = uniqid().'.'.$model->image->extensionName;
            $path = Yii::app()->createAbsoluteUrl('/modules/user/images/avatar/').$newname;//'/var/www/project4/protected/modules/user/images/avatar/'
            $model->avatar = $newname;

            if($model->save())
            {
                // var_dump($_FILES);exit;
                if(isset($model->image))
                {
                    $model->image->saveAs($path);
                }
                Yii::app()->user->setFlash('message',Yii::t('UserModule.base','Profile update success.'));
                $this->redirect(array('profile','id'=>$model->id));

            }
        }
        $this->render('updateOwnProfile',array(
            'model'=>$model,
        ));
    }
}
